package org.csu.jpetstore.controller;

import org.csu.jpetstore.domain.Account;
import org.csu.jpetstore.domain.Cart;
import org.csu.jpetstore.domain.Order;
import org.csu.jpetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("order/")
@SessionAttributes({"order", "isConfirmed", "shippingAddressRequired"})
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    Order order;

    boolean isConfirmed = false;
    boolean shippingAddressRequired = false;

    @GetMapping("help")
    public String help(){
        return "/help";
    }

    @GetMapping("newOrderForm")
    public String newOrderForm(@SessionAttribute("account") Account account, @SessionAttribute("cart") Cart cart, Model model){
        order = orderService.createOrder(account, cart);
        model.addAttribute("order", order);
        model.addAttribute("isConfirmed", isConfirmed);
        model.addAttribute("shippingAddressRequired", shippingAddressRequired);
        return "order/NewOrderForm";
    }

    @GetMapping("shippingForm")
    public String shippingForm(Model model){
        shippingAddressRequired = true;
        model.addAttribute("shippingAddressRequired", shippingAddressRequired);
        return "order/NewOrderForm";
    }

    @GetMapping("confirmOrder")
    public String confirmOrder(Model model){
        isConfirmed = true;
        model.addAttribute("isConfirmed", isConfirmed);
        return "order/NewOrderForm";
    }

    @PostMapping("newOrder")
    public String newOrder(@SessionAttribute("shippingAddressRequired") boolean shippingAddressRequired, @SessionAttribute("isConfirmed") boolean isConfirmed, Model model){
        if(!shippingAddressRequired){
            return "order/ShippingForm";
        }else if(isConfirmed){
            orderService.insertOrder(order);
            model.addAttribute("order", order);
            return "order/ViewOrder";
        }else{
            return "order/ConfirmOrder";
        }
    }
}
